<?php


namespace App\HttpController\Api\System;


use App\HttpController\Api\Base;
use App\HttpController\Router;
use App\Models\NodeModel;
use EasySwoole\Mysqli\QueryBuilder;
use EasySwoole\Validate\Validate;


class Node extends Base
{
    /**
     * @throws \EasySwoole\ORM\Exception\Exception
     * @throws \Throwable
     * 获取所有节点
     */
    public function index()
    {
        $res = NodeModel::create()->order('type', 'asc')->select();
        $allNode = [];
        foreach ($res as $k => $v) {
            switch ($v['type']) {
                case 1:
                    $allNode[$v['node']] = $v;
                    break;
                case 2:
                    $node = dirname($v['node']);
                    $allNode[$node]['sub'][$v['node']] = $v;
                    break;
                case 3:
                    $node = dirname(dirname($v['node']));
                    $allNode[$node]['sub'][dirname($v['node'])]['sub'][$v['id']]= $v;
                    break;
            }
        }
        $this->writeJson(array_values($allNode));
    }

    /**
     * @return bool
     * @throws \EasySwoole\ORM\Exception\Exception
     * @throws \Throwable
     * 刷新节点
     */
    public function refresh()
    {
        $routerObj = new Router();
        $node = $routerObj->getRouteCollector()->getData();
        $node = array_shift($node);
        $node = array_merge($node['POST'] ?? [], $node['GET'] ?? []);
        $system_node = [];
        foreach ($node as $k => $v) {
            $system_node[dirname(dirname($v))] = 0;
            $system_node[dirname($v)] = 0;
            $system_node[$v] = $k;
        }
        $allId = [];
        try {
            foreach ($system_node as $k => $v) {
                $res = NodeModel::create()->where(['node' => $k])->findOne();
                array_push($allId, $res['id']);
                if (empty($res)) {
                    $type = count(explode('/', $k));
                    $NodeModel = new NodeModel([
                        'node' => $k,
                        'route_url' => $v,
                        'type' => $type - 2
                    ]);
                    $id = $NodeModel->save();
                    array_push($allId, $id);
                }
            }
        } catch (\Throwable $t) {
            $this->writeJson($this->error('刷新失败'));
            $this->errorLog($t);
            return false;
        }
        //删除失效的节点
        NodeModel::create()->destroy(function (QueryBuilder $query) use ($allId) {
            $query->where('id', $allId, 'NOT IN');
        });
        $this->writeJson($this->success('刷新成功'));
        return false;
    }

    /**
     * 修改是否加入rabc权限
     */
    public function edit_is_auth()
    {
        $nodeData = $this->request()->getParsedBody();
        $msg = $nodeData['is_auth'] ? '加入' : '取消';
        try {
            NodeModel::create()->where(['id' => $nodeData['id']])->update(['is_auth' => $nodeData['is_auth']]);
            $this->writeJson($this->success($msg . '成功'));
            return false;
        } catch (\Throwable $t) {
            $this->writeJson($this->error($msg . '失败'));
            $this->errorLog($t);
            return false;
        }

    }

    // 设置节点名称
    public function name()
    {
        try {
            NodeModel::create()->where(['id' => $this->requestData['id']])->update(['title' =>$this->requestData['name']]);
            $this->writeJson($this->success('设置成功'));
            return false;
        } catch (\Throwable $t) {
            $this->writeJson($this->error('设置失败'));
            $this->errorLog($t);
            return false;
        }

    }


    protected function getValidateRule(?string $action): ?Validate
    {
        $validate = new Validate();
        switch ($action) {
            case 'edit_is_auth':
                $validate->addColumn('id', '节点id')->required()->numeric()->min(1);
                $validate->addColumn('is_auth', '权限状态')->required()->numeric()->min(0)->max(1);
                break;
            case 'name':
                $validate->addColumn('id', '节点id')->required()->numeric()->min(1);
                $validate->addColumn('name', '节点名称')->required()->lengthMin(1)->lengthMax(50);
                break;
        }
        return $validate;
    }


}
